<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'cardd:kped:carddKpedKpmx:edit'"
    @register="registerDrawer"
    @ok="validMoney"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsCarddKpedCarddKpedKpmxForm">
  import { computed, ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    CarddKpedKpmx,
    carddKpedKpmxForm,
    carddKpedKpmxSave,
  } from '/@/api/cardd/kped/carddKpedKpmx';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('cardd.kped.carddKpedKpmx');
  const { showMessage, createWarningModal } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CarddKpedKpmx>({} as CarddKpedKpmx);
  const syje = ref(0);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增开票明细') : t('编辑开票明细'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('发票编号'),
      field: 'kpmxFpbh',
      component: 'Input',
      componentProps: {
        maxlength: 300,
      },
      required: true,
    },
    {
      label: t('开票日期'),
      field: 'kpmxKprq',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
      },
      required: true,
    },
    {
      label: t('开票单位'),
      field: 'kpmxKpdw',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('金额'),
      field: 'kpmxJe',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        {
          required: true,
          pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
          message: t('请输入一个数值'),
        },
      ],
    },
    {
      label: t('税率'),
      field: 'kpmxSl',
      component: 'Input',
      componentProps: {
        maxlength: 8,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('备注'),
      field: 'kpmxBz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await carddKpedKpmxForm(data);
    record.value = (res.carddKpedKpmx || {}) as CarddKpedKpmx;
    record.value.__t = new Date().getTime();
    syje.value = data.syje;
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function validMoney() {
    try {
      const data = await validate();
      // 是否超过剩余金额
      if (syje.value < data.kpmxJe) {
        createWarningModal({
          title: t('提示'),
          content: t('开票金额不能大于剩余金额，是否继续？'),
          okText: t('继续'),
          onOk: () => {
            handleSubmit(data);
          },
          closable: true,
          cancelText: t('取消'),
          onCancel: () => {
            console.log('cancel');
            return;
          },
        });
        return;
      } else {
        handleSubmit(data);
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSubmit(data) {
    try {
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.kpmxEdid = record.value.kpmxEdid;
      console.log('submit', params, data, record);

      const res = await carddKpedKpmxSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
